package jwtutil

import (
	"GoScaffoldDemo/config"
	"GoScaffoldDemo/utils/logsutil"
	"errors"

	"time"

	"github.com/golang-jwt/jwt/v5"
)

var mySigningKey = []byte(config.JwtSigningKey)

// 1.自定义声明类型
type MyCustomClaims struct {
	UserName string `json:"username"`

	jwt.RegisteredClaims
}

// 2.生成token的函数
func CreatToken(username string) (string, error) {
	claims := MyCustomClaims{
		username,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * time.Duration(config.JwtExpireTime))),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "dotbalo",
			Subject:   "zyk",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(mySigningKey)
	return ss, err
}

func ParseToken(ss string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(ss, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		//解析失败
		logsutil.Error(nil, "解析token失败")
		return nil, err
	} else if claims, ok := token.Claims.(*MyCustomClaims); ok {
		//解析成功

		return claims, nil
	} else {
		//token不合法
		logsutil.Warn(nil, "token不合法")
		return nil, errors.New("token不合法")
	}
}
